package com.mybatisLike.sqlSession;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


import com.mybatisLike.config.Function;
import com.mybatisLike.config.MapperBean;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 读取配置信息
 * @author isam2016
 * @create 2021-08-23 11:35 AM
 */
public class MyConfiguration {
    private  static  ClassLoader loader = ClassLoader.getSystemClassLoader();
    /**
     * 读取数据库配置信息
     * @param resource
     * @return
     */
     public Connection build(String resource){
         InputStream inputStream = loader.getResourceAsStream(resource);
         SAXReader reader = new SAXReader();
         try {
             Document document = reader.read(inputStream);
             Element element = document.getRootElement();
             return evalDataSoource(element);
         } catch (DocumentException e) {
             e.printStackTrace();
             throw new RuntimeException("xml error");
         }
     }

     private Connection evalDataSoource(Element node){
         String driverClassName = null;
         String url = null;
         String username = null;
         String password = null;
         Connection conn = null;
         // 获取属性节点
         for (Object item : node.elements("property")){
            Element i = (Element) item;
            String value = getValue(i);
            String name = i.attributeValue("name");
            if(name == null){
                throw new RuntimeException("elemnt error");
            }
            switch (name){
                case "url":
                    url = value;
                    break;
                case "username":
                    username = value;
                    break;
                case "password":
                    password = value;
                    break;
                case "driverClassName":
                    driverClassName = value;
                    break;
                default:
                    throw new RuntimeException("[database]: <property> unknown name");
            }
         }
         try {
             // 1加载mysql驱动
             Class.forName(driverClassName);
             // 2. 获得数据库连接
             conn = DriverManager.getConnection(url, username, password);
         } catch (ClassNotFoundException e) {
             e.printStackTrace();
         } catch (SQLException e) {
             e.printStackTrace();
         }finally {

         }
         return  conn;
     }
      //获取property属性的值,如果有value值,则读取 没有设置value,则读取内容
      private  String getValue(Element node) {
         return node.hasContent() ? node.getText() : node.attributeValue("value");
     }

    /**
     * mapper 文件
     * @return
     */
     public MapperBean readMapper(String path){
         MapperBean mapperBean = new MapperBean();
         try {
             InputStream inputStream = loader.getResourceAsStream(path);
             SAXReader reader = new SAXReader();
             Document document = reader.read(inputStream);
             Element root = document.getRootElement();
             // mapper 的节点名字
             mapperBean.setInterfaceName(root.attributeValue("nameSpace").trim());
             List<Function> functionList = new ArrayList<>(); // 存储方法
             for (Iterator iterator = root.elementIterator(); iterator.hasNext();){
                 Function function = new Function();
                 Element element = (Element) iterator.next();
                 String sqltype = element.getName().trim();
                 String funcName = element.attributeValue("id").trim();
                 String sql = element.getText().trim();
                 String resultType = element.attributeValue("resultType").trim();
                 function.setSqltype(sqltype);
                 function.setFuncName(funcName);
                 Object newInstance = null;
                 try {
                     // 创建参数类型对象
                     newInstance = Class.forName(resultType).newInstance();
                 } catch (InstantiationException e1) {
                     e1.printStackTrace();
                 } catch (IllegalAccessException e1) {
                     e1.printStackTrace();
                 } catch (ClassNotFoundException e1) {
                     e1.printStackTrace();
                 }
                 function.setResultType(newInstance);
                 function.setSql(sql);
                 functionList.add(function);

             }
             mapperBean.setList(functionList);
         } catch (DocumentException e) {
             e.printStackTrace();
         } finally {
         }
        return mapperBean;
     }
}
